package com.witdata.controller.code;

import com.witdata.common.domain.Result;
import com.witdata.common.domain.Status;
import com.witdata.common.domain.dto.CodeContentDto;
import com.witdata.common.domain.dto.CodeDto;
import com.witdata.framework.service.code.CodeService;
import lombok.RequiredArgsConstructor;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/code")
@RequiredArgsConstructor
public class CodeController {
    private final CodeService codeService;

    @GetMapping("/list")
    public Result<List<CodeDto>> getUserCodeList(@RequestParam("userId") Long userId) {
        List<CodeDto> codeDtoList = codeService.getUserCodeList(userId);
        return Result.ok(Status.SUCCESS, codeDtoList);
    }

    @PostMapping("/create")
    public Result<String> createCodeEnvironment(@RequestBody CodeDto codeDto) {
        codeService.createCodeEnvironment(codeDto);
        return Result.ok(Status.CREATESUCCESS);
    }

    @PostMapping("/stop")
    public Result<String> stopCode(@RequestBody CodeContentDto codeContentDto) {
        codeService.stopCode(codeContentDto);
        return Result.ok(Status.STOPDOCKERSUCCESS);
    }

    @PostMapping("/run")
    public Result<String> runCode(@RequestBody CodeContentDto codeContentDto) {
        if (ObjectUtils.isEmpty(codeContentDto.getCodeId())) return Result.fail(Status.PARAMERROR);
        codeService.runCode(codeContentDto);
        return Result.ok();
    }

    @GetMapping("/info")
    public Result<CodeDto> getCodeInfo(@RequestParam("codeId") Long codeId) {
        CodeDto codeDto = codeService.getCodeInfoByCodeId(codeId);
        return Result.ok(Status.SUCCESS, codeDto);
    }

    @PostMapping("/content/save")
    public Result<String> saveCode(@RequestBody CodeContentDto codeContentDto) {
        codeService.saveContent(codeContentDto);
        return Result.ok(Status.SAVESUCCESS);
    }

    @GetMapping("/content")
    public Result<CodeContentDto> getCodeContent(@RequestParam("codeId") Long codeId) {
        CodeContentDto codeContent = codeService.getCodeContent(codeId);
        if (ObjectUtils.isEmpty(codeContent)) {
            codeContent = new CodeContentDto();
            codeContent.setContent("");
        }
        return Result.ok(Status.SUCCESS, codeContent);
    }
}
